package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.kh.KHUtil
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.jdbc.support.rowset.SqlRowSet

/**
 * @Title: autoGetUserInfo*
 * @Description: 客服促开实时数据*
 * @author: th @date 2022-5-28 14:00:00
 */

class autoKFDBData implements CallBackInvoke {
    private static final Log log = LogFactory.getLog(autoKFDBData.class);

    public void doCallBack(EliteBean eliteBean, String callBack, Map map, String body) {
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        long startTime = System.currentTimeMillis();
        long endTime = 0;

        String Rec_Guid = "";
        String f_Reg_Mobile = "";
        String f_Status = "";
        String f_Operation_Step = "";
        String f_Last_Operation_Time = "";

        int insertNum = 0;
        int loogNum = 0;

        try {
            // 批量更新客户云状态数据
            String selectSQL = '''Select '' As Rec_Guid, R2.f_Reg_Mobile, R2.f_Status, 
                     R2.f_Operation_Step, 
                     Date_Format(R2.f_Last_Operation_Time, '%Y-%m-%d %H:%i:%s') As f_Last_Operation_Time 
                     From Dws.Cloudera_State R2''';


            String updateSQL = "UPDATE Customer R1 SET R1.f_Cloud_State = ?, " +
                    "R1.f_Operation_Step = ?, R1.f_Last_Operation_Time = ? " +
                    "WHERE R1.Mobile = ?";

            long queryStartTime = System.currentTimeMillis();
            SqlRowSet selectRow = jt.queryForRowSet(selectSQL);
            log.debug("促开实时数据查询完成-处理时长(毫秒):" + (System.currentTimeMillis() - queryStartTime));

           // 批量更新参数列表
            List<Object[]> batchArgs = new ArrayList<>();
            int batchSize = 1000; // 每批处理量
            int totalCount = 0;
            int processedCount = 0;

            long processStartTime = System.currentTimeMillis();

            while (selectRow.next()) {
                String fRegMobile = selectRow.getString("f_Reg_Mobile");

                if (!KHUtil.isNull(fRegMobile)) {
                    String fStatus = selectRow.getString("f_Status");
                    String fOperationStep = selectRow.getString("f_Operation_Step");
                    String fLastOperationTime = selectRow.getString("f_Last_Operation_Time");

                    // 添加到批量参数列表
                    String[] cusArr = new String[4]  // 先创建长度为4的数组
                    cusArr[0] = fStatus;
                    cusArr[1] = fOperationStep;
                    cusArr[2] = fLastOperationTime;
                    cusArr[3] = fRegMobile;
                    batchArgs.add(cusArr)         // 添加到参数列表
                    processedCount++;

                    // 达到批量大小时执行更新
                    if (batchArgs.size() >= batchSize) {
                        jt.batchUpdate(updateSQL, batchArgs);
                        totalCount += batchArgs.size();
                        batchArgs.clear();

                        log.debug("已批量处理"+batchSize+" 条记录，累计处理 :"+totalCount);
                    }
                }
            }

          // 处理剩余未达到批量大小的记录
            if (!batchArgs.isEmpty()) {
                jt.batchUpdate(updateSQL, batchArgs);
                totalCount += batchArgs.size();
                log.debug("最后处理，"+batchArgs.size()+"条累计处理:"+totalCount);
            }

            long totalTime = System.currentTimeMillis() - processStartTime;
            log.debug("促开实时数据已成功更新客户资料"+ processedCount+"总处理时长(毫秒):"+totalTime);

            log.debug("--------------------开始执行AI外呼数据--------------------------")
            //1.查询平安期货提供的AI外呼数据 dwd.ai_intention
            List SelectAIList=eliteBean.chaxun_sql("select phone_number From dwd.ai_intention where insert_date=DATE_FORMAT(NOW(),'%Y-%m-%d')","dataSource");

            for (int i=0;i<SelectAIList.size();i++){
                String Mobile=SelectAIList.get(i).get("phone_number");
                //判度提醒表里是否存在改手机号，并且是AI外呼类型的,当天存在则不插入提醒表
                List IsNoticeList=eliteBean.chaxun_sql("SELECT Mobile FROM  hst_leadsnotice where CREATEDDATE >DATE_SUB(CURDATE(),INTERVAL 0 day) and Mobile='"+Mobile+"' and AI_flag='true'","dataSource");

                if (IsNoticeList.size()<=0){
                    //查询该条手机号是否存在促开任务
                    List OBList=eliteBean.chaxun_sql("select e.ELITETASK_GUID,e.OBJECTIVE_GUID,e.CUSTOMER_GUID,e.HANDLEBY_ID,e.HANDLEGROUP_ID  from elitetask e \n" +
                            "left join customer c on c.customer_guid=e.customer_guid \n" +
                            "where c.MOBILE='"+Mobile+"'\n" +
                            "and e.MAP_ID='4CA2PP'\n" +
                            "limit 1 ","dataSource");

                    if (OBList.size()>0){
                        String CUSTOMER_GUID=OBList.get(0).get("CUSTOMER_GUID");
                        String ELITETASK_GUID=OBList.get(0).get("ELITETASK_GUID");
                        String OBJECTIVE_GUID=OBList.get(0).get("OBJECTIVE_GUID");
                        String HANDLEBY_ID=OBList.get(0).get("HANDLEBY_ID");
                        String HANDLEGROUP_ID=OBList.get(0).get("HANDLEGROUP_ID");
                        //插入提醒表咯
                        eliteBean.update("insert into hst_leadsnotice(noticeId,noticeGroup,noticeBy,createGroup,createBy,\n" +
                                "    noticeContent,createddate,limitCount,loadCount,noticeType,\n" +
                                "   objective_guid,subscribedate,Customer_guid,Elitetask_guid,mobile,AI_flag)\n" +
                                "   values(UUID(),'"+HANDLEGROUP_ID+"','"+HANDLEBY_ID+"','"+HANDLEGROUP_ID+"','"+HANDLEBY_ID+"',\n" +
                                "   '您有一条AI外呼的外拨任务，请及时处理！',NOW(),1,0,'7','"+OBJECTIVE_GUID+"',\n" +
                                "     now(),'"+CUSTOMER_GUID+"',\n" +
                                "   '"+ELITETASK_GUID+"','"+Mobile+"','true');","dataSource");
                    }else{
                        log.debug("该条手机号没有促开任务："+Mobile);

                    }


                }else{
                    log.debug("该条手机号当日已经存在AI外呼拨打任务："+Mobile);
                }
            }


        } catch (Exception e) {
            log.error("[" + loogNum + "]同步平安数据到过河兵异常!", e);
        }
    }
}